
#include <QApplication>
#include <QTextEdit>
#include <QTextBrowser>
#include <QSqlDatabase>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QSqlError>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextBrowser edit;
    edit.setWindowTitle("QTextBrowser测试");

    //连接数据库
    //新建数据库表格
    auto db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("yhdn.cn");
    db.setUserName("admin");
    db.setPassword("Stallman7*");
    db.setDatabaseName("world");
    if(!db.open()){
        qDebug() << db.lastError().text();
        return 0;
    }

    //获取数据库的数据

    QString css = R"(
        table{min-width:1200px;border-collapse: collapse;margin:30px 10px}
        th,td{border:1px solid darkgreen;font-size:12px;padding:5px 20px}
        th{padding:10px 30px;background-color:#ddd}
)";

    QSqlQuery query;
    QString thead,tbody;
    QString sql = "SELECT "
                  "id,name,"
                  "details->>'$.cpu' as cpu,"
                  "details->>'$.mb' as mainborad,"
                  "details->>'$.ssd' as ssd,"
                  "details->>'$.hdd' as hdd,"
                  "details->>'$.vga' as vga"
                  " from dn;";
    bool ret = query.exec(sql);
    auto record_empty = query.record();
    thead+=("<tr>");
    for (int i=0;i<record_empty.count();i++){
        thead+=QString("<th>%1</th>").arg(record_empty.fieldName(i));
    }
    thead+=("</tr>");


    if (!ret)
        qDebug() << query.lastError().text();
    while (query.next()) {

        auto record =  query.record();
        tbody +="<tr>";
        for(int i=0;i<record.count();i++){
            tbody += QString("<td>%1</td>").arg(record.value(i).toByteArray());
        }

        tbody+="</tr>";
    }

    //设置表格
    QString html = QObject::tr(R"(<style>%1</style>
<div style="width:100%;text-align:center">
<table><thead>%2</thead><tbody>%3</tbody></table></div>)").arg(css,thead,tbody);


    // QString html = "<div style='wi"
    //                "></div>";


    edit.setHtml(html);
    edit.setMinimumSize(1000,600);
    edit.show();
    return a.exec();
}
